﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using FSS.Core.Util;
using FSS.Core.Controls;
using FSS.BLL.Services;
using FSS.BLL.Entities;

namespace SalesManagement.Modules.Warehouse
{
    public partial class StockTransfer : BasePage
    {
        public StockTransfer()
            : base(SCREENS.STOCKTRANFER)
        {

        }
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// Khi load page success
        /// </summary>
        [DirectMethod]
        public void DocumentReady()
        {

            LoadWarehouse();
            LoadEmployee();
            BindingUnit();
            NewDataProcess();
        }

        /// <summary>
        /// Load Kho hàng
        /// </summary>
     
        private void LoadWarehouse()
        {
            WareHouseEntity warehouseE = new WareHouseEntity();
            WareHouseService warehouseS = WareHouseService.GetInstance();
            IList<WareHouseEntity> lstWarehouse = warehouseS.LoadAll();
            if (null != lstWarehouse)
            {
                this.storeWarehouse.DataSource = lstWarehouse;
                this.storeWarehouse.DataBind();
            }
        }
        /// <summary>
        /// Load nhan vien
        /// </summary>

        private void LoadEmployee()
        {
            EmployeeEntity employeeE = new EmployeeEntity();
            EmployeeService employeeS = EmployeeService.GetInstance();
            IList<EmployeeEntity> lstEmployee = employeeS.LoadAll();
            if (null != lstEmployee)
            {
                this.storeEmployee.DataSource = lstEmployee;
                this.storeEmployee.DataBind();
            }
        }
        /// <summary>
        /// Binding Đơn vị tính
        /// </summary>
        private void BindingUnit()
        {
            UnitService service = UnitService.GetInstance();
            IList<UnitEntity> Resul = service.LoadAll();
            if (Resul == null)
                return;
            stUnit.DataSource = Resul;
            stUnit.DataBind();

        }
        //
        [DirectMethod]
        public bool CheckExistProduct(int productId)
        {
            VoucherDetailEntity voucherDetailE = new VoucherDetailEntity();
            voucherDetailE.VoucherId = Util.Obj2Int(hdDocumentID.Value);
            voucherDetailE.ProductId = productId;
            VoucherDetailService voucherDetailS = VoucherDetailService.GetInstance();
            if (voucherDetailS.CheckExistProduct(voucherDetailE))
            {
                return false;
            }
            return true;
        }

        #region HandleSave
        /// <summary>
        /// Save Phiếu chuyển kho
        /// </summary>
        [DirectMethod]
        public bool SaveVoucher()
        {
            try
            {
                VoucherEntity VoucherE = getVoucherEntity();
                Int64 VoucherId = insertUpateVoucher(VoucherE);
                if (VoucherId < 0)
                    return false;
                else hdDocumentID.Text = VoucherId.ToString();
                return true;
            }
            catch (Exception ex)
            {
                return false;
                throw ex;
            }

        }

        private void BindingDocument()
        {
            Int64 VoucherId = Util.Obj2Long(hdDocumentID.Text);
            if (VoucherId > 0)
            {
                VoucherService voucherS = VoucherService.GetInstance();
                VoucherEntity voucherE = voucherS.GetEntityByPrimaryKey(VoucherId);
                if (voucherE == null)
                    return;
                VoucherDetailService voucherDetailS = VoucherDetailService.GetInstance();
                IList<VoucherDetailEntity> lstDetail = voucherDetailS.GetAllDetailTranferStockByMasterID(VoucherId);
                stDetail.DataSource = lstDetail;
                stDetail.DataBind();
                btnAdd.Disabled = false;
            }
            else
                NewDataProcess();

        }
        /// <summary>
        /// Save Chi tiết chuyển kho
        /// </summary>
        [DirectMethod]
        public void SaveVoucherDetail(string JsonDetail)
        {
            try
            {
                int voucherId = Util.Obj2Int(hdDocumentID.Value);
                if (!string.IsNullOrEmpty(JsonDetail))
                {
                    string jsonGrouptOther = String.Format("{{{0}}}", JsonDetail);
                    jsonGrouptOther = jsonGrouptOther.Replace(",{}", "").Replace("[{}]", "");
                    StoreDataHandler dataGrouptOther = new StoreDataHandler(jsonGrouptOther);
                    ChangeRecords<VoucherDetailEntity> data = dataGrouptOther.ObjectData<VoucherDetailEntity>();
                    VoucherDetailService voucherDetailS = VoucherDetailService.GetInstance();
                    foreach (VoucherDetailEntity _voucherDetailE in data.Updated)
                    {
                        _voucherDetailE.VoucherId = voucherId;
                        InsertDetail(_voucherDetailE);

                    }
                    foreach (VoucherDetailEntity _voucherDetailE in data.Created)
                    {
                        _voucherDetailE.VoucherId = voucherId;
                        InsertDetail(_voucherDetailE);
                    }
                    foreach (VoucherDetailEntity _voucherDetailE in data.Deleted)
                    {
                        _voucherDetailE.VoucherId = voucherId;
                        voucherDetailS.Delete(_voucherDetailE);
                    }
                    VoucherEntity VoucherE = getVoucherEntity();
                    VoucherE.Status = Constants.POSTING;
                    insertUpateVoucher(VoucherE);
                }
                BindingDocument();
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        private long insertUpateVoucher(VoucherEntity voucherE)
        {

            VoucherService voucherS = VoucherService.GetInstance();
            Int64 VoucherId = Format.ConvertToLong(hdDocumentID.Text);
            if (VoucherId > 0)
                voucherE.VoucherId = VoucherId;
            VoucherId = voucherS.InsertUpdate(voucherE);
            return VoucherId;
        }
        private void InsertDetail(VoucherDetailEntity voucherDetailE)
        {
            try
            {
                VoucherDetailService voucherDetailS = VoucherDetailService.GetInstance();
                if (voucherDetailE.VoucherDetailId > 0)
                {
                    voucherDetailS.DeleteVoucherTransferStock(voucherDetailE.VoucherId, voucherDetailE.ProductId);
                }
                voucherDetailE.CreatedBy = 1;
                voucherDetailE.UpdatedBy = 1;
                voucherDetailE.IsInput = false;

                voucherDetailE.BasicQuantity = voucherDetailE.Quantity;
                voucherDetailE.BasicUnitId = voucherDetailE.UnitId;
                voucherDetailE.BasicUnitPrice = voucherDetailE.UnitPrice;

                if (voucherDetailE.VATPercent == null)
                {
                    voucherDetailE.VATPercent = 0;
                    voucherDetailE.VATAmount = 0;
                }
                if (voucherDetailE.DiscountPercent == null)
                {
                    voucherDetailE.DiscountPercent = 0;
                    voucherDetailE.DiscountAmount = 0;
                }
                voucherDetailE.Amount = voucherDetailE.Quantity * voucherDetailE.UnitPrice;
                voucherDetailE.UpdatedDate = DateTime.Now;
                voucherDetailE.CreatedDate = DateTime.Now;
                voucherDetailE.ExpiryDate = DateTime.Now;

                voucherDetailE.WarehouseId = Util.Obj2Int(cboFromWarehouse.Value);
                VoucherDetailEntity _voucherDetailE = new VoucherDetailEntity();
                _voucherDetailE = voucherDetailE;
                voucherDetailS.InsertUpdate(voucherDetailE);
                _voucherDetailE.IsInput = true;
                _voucherDetailE.WarehouseId = Util.Obj2Int(cboToWarehouse.Value);
                voucherDetailS.InsertUpdate(_voucherDetailE);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected void grDetail_OnAfterEdit(object sender, DirectEventArgs e)
        {
            try
            {
                VoucherEntity VoucherE = getVoucherEntity();
                VoucherE.Status = Constants.DRAFT;
                insertUpateVoucher(VoucherE);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private VoucherEntity getVoucherEntity()
        {
            VoucherEntity Resul = new VoucherEntity();
            Resul.VoucherNo = txtVoucherNo.Text.Trim();
            if (txtVoucherDate.SelectedValue != null)
                Resul.VocherDate = txtVoucherDate.SelectedDate;
            else Resul.VocherDate = DateTime.Now;
            if (cboFromWarehouse.SelectedItem.Value != null)
                Resul.WarehouseId = Util.Obj2Int(cboFromWarehouse.Value);
            if (cboToWarehouse.SelectedItem.Value != null)
                Resul.ToWarehouseId = Util.Obj2Int(cboToWarehouse.Value);
            if (cboToWarehouse.SelectedItem.Value != null)
                Resul.CreatedBy = Util.Obj2Int(cboToWarehouse.Value); ;
            Resul.BranchId = 1;
            Resul.UpdatedBy = 1;
            Resul.UpdatedDate = DateTime.Now;
            Resul.CreatedDate = DateTime.Now;
            Resul.VoucherType = Constants.VoucherType.PCK.ToString();
            Resul.Status = Constants.DRAFT;
            return Resul;
        }
        #endregion

        /// <summary>
        /// Xóa dữ liệu cho thêm mới
        /// </summary>
        [DirectMethod]
        public bool NewDataProcess()
        {
            txtVoucherDate.Value = DateTime.Now;
            GetVoucherNo(Constants.VoucherType.PCK.ToString());
            hdDocumentID.Text = "";
            var store = this.grDetail.GetStore();
            store.DataSource = new List<VoucherDetailEntity>();
            store.DataBind();
            btnAdd.Disabled = true;
            return true;
        }
        [DirectMethod]
        public bool DeleteProcess() {
            long voucherId = Util.Obj2Long(hdDocumentID.Value);
            if (voucherId > 0)
            {
                VoucherEntity voucherE = new VoucherEntity();
                VoucherService voucherS = VoucherService.GetInstance();
                VoucherDetailService voucherDetailS = VoucherDetailService.GetInstance();
                voucherDetailS.DeleteVoucherDetailByVoucherId(voucherId);
                voucherS.Delete(voucherId);
                //NewDataProcess();
                return true;
            }
            return false;
        }
        private void GetVoucherNo(string strVoucherType)
        {
            ConfigNumberService _configNumberS = ConfigNumberService.GetInstance();
            txtVoucherNo.Text = _configNumberS.GetNumberCode(strVoucherType);
        }
        protected void grdMain_OnCommand(object sender, DirectEventArgs e) { }
        public void btnAdd_Click(object sender, DirectEventArgs e)
        {
            NewDataProcess();
        }
        public void btnEdit_Click(object sender, DirectEventArgs e) { }
        public void btnDelete_Click(object sender, DirectEventArgs e) {
            
           
        }
        public void btnFind_Click(object sender, DirectEventArgs e) { }
    }
}
